package cn.jasonone.jame.scene;

import cn.hutool.core.util.IdUtil;
import cn.jasonone.jame.GameScene;
import cn.jasonone.jame.JameApplication;
import cn.jasonone.jame.basic.GameContext;
import cn.jasonone.jame.model.Spirit;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

/**
 * 卷轴场景
 *
 * @author Jason
 * @since 1.0.0
 */
public class ScrollGameScene extends GameScene {
    /**
     * 当前显示的图片
     */
    private int index;
    /**
     * 是否水平移动
     */
    @Setter(AccessLevel.PROTECTED)
    @Getter
    private boolean horizontal;
    /**
     * 移动速度
     */
    @Setter(AccessLevel.PROTECTED)
    @Getter
    private int speed;

    private Spirit[] spirits;

    public ScrollGameScene(double width, double height) {
        super("ScrollGameScene_"+ IdUtil.fastUUID(),width, height);
    }

    @Override
    public void init(GameContext<JameApplication> gc) {
        super.init(gc);
        for (Spirit spirit : this.getSpirits()) {
            spirit.setSize(getWidth(),getHeight());
        }
    }

    protected void setImages(Image... images) {
        this.spirits=new Spirit[images.length];
        for (int i = 0; i < images.length; i++) {
            Spirit spirit = new Spirit(images[i]);
            spirit.setId("__SCROLL_GAME_SCENE_"+i+"__");
            spirit.setFloor(Integer.MIN_VALUE);
            spirit.move(0,-spirit.getHeight()*i);
            this.spirits[i]=spirit;
            this.append(spirit);
        }
    }

    @Override
    public void draw(GraphicsContext gc) {
        for (Spirit spirit : this.spirits) {
            if(spirit.getId().startsWith("__SCROLL_GAME_SCENE_")){
                if (horizontal) {
                    spirit.move(this.speed, 0);
                } else {
                    spirit.move(0, this.speed);
                }
            }
        }
        //获取第一张图片
        Spirit spirit = this.spirits[index];
        index = index + 1 >= this.spirits.length ? 0 : index+1;
        if (!this.getRect().isCollision(spirit)){
            //如果当前图片移出屏幕
            index = index + 1 >= this.spirits.length ? 0 : index+1;
            spirit = this.spirits[index];
            //将下一张显示的图片放到屏幕之外准备显示
            spirit.moveTo(0,-spirit.getHeight());
        }
        super.draw(gc);
    }
}
